<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { ElButton, ElMessage } from 'element-plus'

import { Table } from '@/components/Table'
import { purchaseIndex, purchaseDEL, purchaseSubmit } from '@/api/common'
import { useTable } from '@/hooks/web/useTable'
import { purchaseType } from '@/api/common/types'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, reactive } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useRouter } from 'vue-router'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}
const { t } = useI18n()

// defineOptions({
//   name: 'purchaseOrder'
// })

const { push } = useRouter()

const { register, tableObject, methods } = useTable<purchaseType>({
  getListApi: purchaseIndex,
  delListApi: purchaseDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: userRlues.includes('201') ? -1 : userId
})

const { getList, setSearchParams } = methods

getList()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'shippingOrderSettings',
    label: t('shippingOrderSettings.packagingCalculationSettings'),
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          {
            label: '按件系数',
            value: '1'
          },
          {
            label: '体积系数',
            value: '2'
          }
        ]
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  },
  {
    field: 'shippingOrderSettings',
    label: t('shippingOrderSettings.PleaseSelectTheAmountType'),
    search: {
      show: true,
      component: 'Select',
      componentProps: {
        filterable: true,
        options: [
          {
            label: '按重量',
            value: '1'
          },
          {
            label: '按体积',
            value: '2'
          },
          {
            label: '按个数',
            value: '3'
          }
        ]
      }
    },
    form: {
      colProps: {
        span: 24
      }
    },
    detail: {
      span: 24
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const AddAction = () => {
  push('/logistics/purchaseOrderAdd')
}

const delLoading = ref(false)
const getArr = (selections) => {
  let a = ''
  selections.map((v) => (a += v.id + ','))
  return a
}

const delData = async (row: purchaseType | null, multiple: boolean, rlus: string) => {
  if (!checkRlues(rlus)) return false

  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? getArr(selections) : (tableObject.currentRow?.id as string),
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const action = async (row: purchaseType, type: string, rlus: string) => {
  if (!checkRlues(rlus)) return false

  if (type == 'Edit') {
    push(`/logistics/purchaseOrder${type}?id=${row.id}`)
  }
  if (type == 'Submit') {
    const res = await purchaseSubmit('' + row.id)
    if (res) {
      ElMessage.success('提交成功')
    }
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :model="{ title: '' }"
      :schema="allSchemas.searchSchema"
      @search="setSearchParams"
      @reset="setSearchParams"
    />

    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'Submit', '6-2')">
          {{ t('purchaseOrder.submitForReview') }}
        </ElButton>
        <ElButton type="primary" @click="action(row, 'Edit', '6-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '6-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>
</template>
